const db = require('../config/db')
const io = require('../sql/socket/index')
    // 添加好友
const addfriends = (req, res) => {
        // u_id 申请方id
        let { f_id, u_id, user_name, user_age, user_email, user_img, group_val, msg, Uname } = req.body
        console.log(req.body);
        let time = new Date().getFullYear() + '-' + (new Date().getMonth() + 1) + '-' + new Date().getDate() + '-' + new Date().getHours() + ':' + new Date().getMinutes() + ':' + new Date().getSeconds()
        db.query('SELECT * FROM friends', (err, resp) => {
            if (err) return res.send({ code: 500, msg: err.sqlMessage })
            db.query('SELECT * FROM chat', (err, chatresp) => {
                if (err) return res.send({ code: 500, msg: err.sqlMessage })
                const chatfind = chatresp.find(item => item.f_id == f_id && item.u_id == u_id && item.chat_val == '好友申请')
                if (chatfind) {

                    db.query(`update chat set chat_to = '${    chatfind.chat_to++}' where chat_id =${chatfind.chat_id}`, (err) => {
                        if (err) return res.send({ code: 500, msg: err.sqlMessage })
                        io.sockets.emit(`index${f_id}`, { type: 1, name: '好友申请', lei: Uname, msg, time, to: 1, f_id: u_id, img: user_img })
                    })
                } else {
                    db.query('insert into chat(f_id,u_id,chat_val,chat_io,chat_to,chat_name,chat_email,chat_img) value(?,?,?,?,?,?,?,?)', [f_id, u_id, '好友申请', 0, 1, user_name, user_email, user_img])
                    io.sockets.emit(`index${f_id}`, { type: 0, name: '好友申请', lei: Uname, msg, time, to: 1, f_id: u_id, img: user_img })
                }
                const friendsfind = resp.find(item => item.f_id == f_id && item.u_id == u_id)
                if (friendsfind) {
                    db.query(`update friends set group_val = '${group_val}' where friends_id =${friendsfind.friends_id}`)

                    res.send({ code: 200, msg: '您已申请，待对方同意' })
                    return
                }
                db.query('insert into friends(f_id,u_id,friends_name,friends_age,friends_email,friends_img,group_val,io) value(?,?,?,?,?,?,?,?)', [f_id, u_id, user_name, user_age, user_email, user_img, group_val, 0], (err, resp) => {
                    if (err) return res.send({ code: 500, msg: err.sqlMessage })
                    res.send({ code: 200, msg: '发送成功' })
                })
            })
        })
    }
    // 同意好友
const yesfriends = (req, res) => {

    let { f_id, u_id, user_name, user_age, user_email, user_img, group_val, msg, f_inof } = req.body

    db.query('SELECT * FROM friends', (err, friendsresp) => {
        if (err) return res.send({ code: 500, msg: err.sqlMessage })
        const firendFind = friendsresp.find(item => item.f_id == u_id && item.u_id == f_id)
        console.log(req.body);
        db.query(`update friends set io = '${1}' where friends_id =${firendFind.friends_id}`)
        db.query('insert into friends(f_id,u_id,friends_name,friends_age,friends_email,friends_img,group_val,io) value(?,?,?,?,?,?,?,?)', [f_id, u_id, user_name, user_age, user_email, user_img, group_val, 1], (err, resp) => {
            if (err) return res.send({ code: 500, msg: err.sqlMessage })
            db.query('SELECT * FROM chat', (err, chatresp) => {
                if (err) return res.send({ code: 500, msg: err.sqlMessage })
                const chatfind = chatresp.find(item => item.f_id == u_id && item.u_id == f_id && item.chat_val == '好友申请')
                let time = new Date().getFullYear() + '-' + (new Date().getMonth() + 1) + '-' + new Date().getDate() + '-' + new Date().getHours() + ':' + new Date().getMinutes() + ':' + new Date().getSeconds()

                if (chatfind) {
                    const chat = { type: 0, title: 'ws', msg: '我们已经是好友啦', time, img: user_img }
                    db.query(`update chat set chat_val = '我们已经是好友啦' where chat_id =${chatfind.chat_id}`, (err) => {
                        if (err) return res.send({ code: 500, msg: err.sqlMessage })
                            // 申请方
                        io.sockets.emit(`index${f_id}`, { type: 0, img: f_inof.user_img, title: 'ws', name: f_inof.user_name, msg: '我们已经是好友啦', lei: '我们已经是好友啦', time, to: chatfind.chat_to, u_id, inof: chatfind, id: u_id, chat, })
                            // 同意方
                        io.sockets.emit(`index${u_id}`, { type: 0, title: 'ws', name: user_name, msg: '我们已经是好友啦', lei: '我们已经是好友啦', chat, time, to: chatfind.chat_to, img: user_img, inof: req.body, id: f_id })
                    })
                }
                res.send({ code: 200, msg: '已同意' })
            })
        })

    })

}

// email || name 搜索
const searchUser = (req, res) => {
        let { user_email, user_name } = req.body

        db.query('SELECT * FROM user', (err, resp) => {
            if (err) return res.send({ code: 500, msg: err.sqlMessage })

            const obj = resp.find(item => item.user_email == user_email || item.user_name == user_name)
            if (obj) delete obj.user_passwored
            obj ? res.send({ code: 200, msg: '查找成功', data: obj }) : res.send({ code: 201, msg: '未找到此用户' })
        })
    }
    // id查询用户信息
const userInof = (req, res) => {
    let { f_id, u_id } = req.body
    db.query(`SELECT * from user where id =(${f_id})`, (err, resp) => {
        if (err) return res.send({ code: 500, msg: err.sqlMessage })
        delete resp[0].user_passwored

        db.query('SELECT * FROM friends', (err, resps) => {
            const obj = resps.find(item => item.f_id == f_id && item.u_id == u_id && item.io == 1)

            if (obj && obj.io == 1) return res.send({
                code: 200,
                msg: '此用户',
                data: resp[0],
                to: 1
            })
            res.send({ code: 200, msg: '成功', data: resp[0], to: 0 })
        })
    })
}

// 创建分组
const addGroup = (req, res) => {

        let { group_val, u_id } = req.body

        db.query('insert into `group`(group_val,u_id) value(?,?)', [group_val, u_id], err => {
            if (err) return res.send({ code: 500, msg: err.sqlMessage })
            res.send({ code: 200, msg: '创建成功', })
        })


    }
    // 查询分组
const groupQuery = (req, res) => {

        db.query("SELECT * from `group` where u_id =" + req.query.id, (err, resp) => {
            if (err) return res.send({ code: 500, msg: err.sqlMessage })
            res.send({ code: 200, msg: '查询成功', data: resp, })
        })
    }
    // 查询好友列表
const queryFriendsList = (req, res) => {
    console.log(req.query.id);
    db.query("SELECT * from `friends` where u_id =" + req.query.id, async(err, resp) => {
        if (err) return res.send({ code: 500, msg: err.sqlMessage })

        let arr = []
        await resp.forEach(item => {
            if (item.group_val && item.io == 1) {

                const titleFind = arr.find(itemy => itemy.title == item.group_val)

                if (titleFind) return titleFind.ch.push(item)

                arr.push({ title: item.group_val, ch: [item] })


            }
        })

        res.send({ code: 200, msg: '查询成功', data: arr })
    })
}


const userId = (req, res) => {
    console.log(req.query, );
    db.query("SELECT * from `user` where id =" + req.query.id, (err, resp) => {
        if (err) return res.send({ code: 500, msg: err.sqlMessage })

        res.send({ code: 200, msg: '查询成功', data: resp })

    })

}
const editUser = (req, res) => {
    let { MobilePhoneNumber, personalizedSignature, Gender, age, id, img, names } = req.body
    db.query(`update  user set user_age = "${age}", user_gender ="${Gender}", user_personalizedsignature = "${personalizedSignature}", user_mobilephonenumber="${MobilePhoneNumber}", user_img="${img}", user_name="${names }"  where id =${id}`, (err) => {
        if (err) return res.send({ code: 500, msg: err.sqlMessage })
        res.send({ code: 200, msg: '修改成功', })
    })
}

module.exports = { editUser, userId, addfriends, searchUser, userInof, addGroup, groupQuery, queryFriendsList, yesfriends }